<template>
  <div class="responsibility-management-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>责任管理</h2>
      <p>水库责任体系建设与人员职责管理</p>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon total">
                <el-icon><User /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-value">{{ statistics.totalPersonnel }}</div>
                <div class="stats-label">责任人员总数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon active">
                <el-icon><CircleCheck /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-value">{{ statistics.activeResponsibilities }}</div>
                <div class="stats-label">在岗责任</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon pending">
                <el-icon><Clock /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-value">{{ statistics.pendingTasks }}</div>
                <div class="stats-label">待办任务</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon completed">
                <el-icon><SuccessFilled /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-value">{{ statistics.completedTasks }}</div>
                <div class="stats-label">已完成任务</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 功能标签页 -->
    <el-card class="main-content">
      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <!-- 责任清单 -->
        <el-tab-pane label="责任清单" name="responsibilities">
          <div class="tab-content">
            <!-- 查询条件 -->
            <el-card shadow="hover" style="margin-bottom: 8px">
              <el-form :model="responsibilityQuery" inline>
                <el-form-item label="责任名称">
                  <el-input
                    v-model="responsibilityQuery.name"
                    placeholder="请输入责任名称"
                    clearable
                    style="width: 200px"
                  />
                </el-form-item>
                <el-form-item label="责任类型">
                  <el-select v-model="responsibilityQuery.type" placeholder="请选择类型" clearable style="width: 150px">
                    <el-option label="安全责任" value="safety" />
                    <el-option label="运行责任" value="operation" />
                    <el-option label="维护责任" value="maintenance" />
                    <el-option label="管理责任" value="management" />
                  </el-select>
                </el-form-item>
                <el-form-item label="责任级别">
                  <el-select v-model="responsibilityQuery.level" placeholder="请选择级别" clearable style="width: 120px">
                    <el-option label="一级" value="1" />
                    <el-option label="二级" value="2" />
                    <el-option label="三级" value="3" />
                  </el-select>
                </el-form-item>
                <el-form-item label="状态">
                  <el-select v-model="responsibilityQuery.status" placeholder="请选择状态" clearable style="width: 120px">
                    <el-option label="有效" value="active" />
                    <el-option label="暂停" value="suspended" />
                    <el-option label="废止" value="abolished" />
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="searchResponsibilities">
                    <el-icon><Search /></el-icon>
                    查询
                  </el-button>
                  <el-button @click="resetResponsibilityQuery">
                    <el-icon><Refresh /></el-icon>
                    重置
                  </el-button>
                </el-form-item>
              </el-form>
            </el-card>

            <!-- 操作按钮 -->
            <el-card class="operation-card" shadow="hover" style="margin-bottom: 8px">
              <el-row :gutter="10">
                <el-col :span="24">
                  <el-button type="primary" plain @click="handleAddResponsibility">
                    <el-icon><Plus /></el-icon>
                    新增责任
                  </el-button>
                  <el-button type="success" plain @click="exportResponsibilities">
                    <el-icon><Download /></el-icon>
                    导出清单
                  </el-button>
                  <el-button type="info" plain @click="responsibilityMatrix">
                    <el-icon><Grid /></el-icon>
                    责任矩阵
                  </el-button>
                </el-col>
              </el-row>
            </el-card>

            <!-- 责任清单表格 -->
            <el-card shadow="hover">
              <el-table :data="responsibilityList" border>
                <el-table-column prop="name" label="责任名称" width="200" show-overflow-tooltip />
                <el-table-column prop="code" label="责任编号" width="150" />
                <el-table-column prop="type" label="责任类型" width="120">
                  <template #default="{ row }">
                    <el-tag :type="getResponsibilityTypeTag(row.type)">
                      {{ getResponsibilityTypeText(row.type) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="level" label="责任级别" width="100">
                  <template #default="{ row }">
                    <el-tag :type="getLevelTag(row.level)">
                      {{ getLevelText(row.level) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="description" label="责任描述" min-width="200" show-overflow-tooltip />
                <el-table-column prop="department" label="归属部门" width="120" />
                <el-table-column prop="assignedCount" label="分配人数" width="100" />
                <el-table-column prop="status" label="状态" width="100">
                  <template #default="{ row }">
                    <el-tag :type="getStatusTag(row.status)">
                      {{ getStatusText(row.status) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间" width="160" />
                <el-table-column label="操作" width="270" fixed="right">
                  <template #default="{ row }">
                    <el-button link type="primary" @click="handleViewResponsibility(row)">
                      <el-icon><View /></el-icon>
                      查看
                    </el-button>
                    <el-button link type="primary" @click="handleEditResponsibility(row)">
                      <el-icon><Edit /></el-icon>
                      编辑
                    </el-button>
                    <el-button link type="success" @click="assignResponsibility(row)">
                      <el-icon><UserFilled /></el-icon>
                      分配
                    </el-button>
                    <el-button link type="danger" @click="deleteResponsibility(row)">
                      <el-icon><Delete /></el-icon>
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>

              <!-- 分页 -->
              <div class="pagination-section">
                <Pagination
                  :total="responsibilityPagination.total"
                  v-model:page="responsibilityPagination.currentPage"
                  v-model:limit="responsibilityPagination.pageSize"
                  @pagination="handleResponsibilityPagination"
                />
              </div>
            </el-card>
          </div>
        </el-tab-pane>

        <!-- 人员分配 -->
        <el-tab-pane label="人员分配" name="assignments">
          <div class="tab-content">
            <!-- 查询条件 -->
            <el-card shadow="hover" style="margin-bottom: 8px">
              <el-form :model="assignmentQuery" inline>
                <el-form-item label="人员姓名">
                  <el-input
                    v-model="assignmentQuery.name"
                    placeholder="请输入人员姓名"
                    clearable
                    style="width: 200px"
                  />
                </el-form-item>
                <el-form-item label="所属部门">
                  <el-select v-model="assignmentQuery.department" placeholder="请选择部门" clearable style="width: 150px">
                    <el-option label="管理部" value="management" />
                    <el-option label="运行部" value="operation" />
                    <el-option label="维护部" value="maintenance" />
                    <el-option label="安全部" value="safety" />
                  </el-select>
                </el-form-item>
                <el-form-item label="职位">
                  <el-input
                    v-model="assignmentQuery.position"
                    placeholder="请输入职位"
                    clearable
                    style="width: 150px"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="searchAssignments">
                    <el-icon><Search /></el-icon>
                    查询
                  </el-button>
                  <el-button @click="resetAssignmentQuery">
                    <el-icon><Refresh /></el-icon>
                    重置
                  </el-button>
                </el-form-item>
              </el-form>
            </el-card>

            <!-- 操作按钮 -->
            <el-card class="operation-card" shadow="hover" style="margin-bottom: 8px">
              <el-row :gutter="10">
                <el-col :span="24">
                  <el-button type="primary" plain @click="handleAddAssignment">
                    <el-icon><Plus /></el-icon>
                    新增分配
                  </el-button>
                  <el-button type="warning" plain @click="batchAssign">
                    <el-icon><Operation /></el-icon>
                    批量分配
                  </el-button>
                  <el-button type="success" plain @click="exportAssignments">
                    <el-icon><Download /></el-icon>
                    导出分配
                  </el-button>
                </el-col>
              </el-row>
            </el-card>

            <!-- 人员分配表格 -->
            <el-card shadow="hover">
              <el-table :data="assignmentList" border>
                <el-table-column type="selection" width="55" />
                <el-table-column prop="name" label="人员姓名" width="120" />
                <el-table-column prop="employeeId" label="工号" width="120" />
                <el-table-column prop="department" label="所属部门" width="120" />
                <el-table-column prop="position" label="职位" width="120" />
                <el-table-column prop="responsibilities" label="分配责任" min-width="200">
                  <template #default="{ row }">
                    <el-tag
                      v-for="responsibility in row.responsibilities"
                      :key="responsibility"
                      size="small"
                      type="info"
                      effect="plain"
                      style="margin-right: 5px; margin-bottom: 5px;"
                    >
                      {{ responsibility }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="responsibilityCount" label="责任数量" width="100" />
                <el-table-column prop="phone" label="联系电话" width="130" />
                <el-table-column prop="assignDate" label="分配时间" width="160" />
                <el-table-column label="操作" width="270" fixed="right">
                  <template #default="{ row }">
                    <el-button link type="primary" @click="viewAssignmentDetail(row)">
                      <el-icon><View /></el-icon>
                      查看
                    </el-button>
                    <el-button link type="primary" @click="handleEditAssignment(row)">
                      <el-icon><Edit /></el-icon>
                      编辑
                    </el-button>
                    <el-button link type="warning" @click="adjustAssignment(row)">
                      <el-icon><Setting /></el-icon>
                      调整
                    </el-button>
                    <el-button link type="danger" @click="deleteAssignment(row)">
                      <el-icon><Delete /></el-icon>
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>

              <!-- 分页 -->
              <div class="pagination-section">
                <Pagination
                  :total="assignmentPagination.total"
                  v-model:page="assignmentPagination.currentPage"
                  v-model:limit="assignmentPagination.pageSize"
                  @pagination="handleAssignmentPagination"
                />
              </div>
            </el-card>
          </div>
        </el-tab-pane>

        <!-- 考核评价 -->
        <el-tab-pane label="考核评价" name="evaluation">
          <div class="tab-content">
            <!-- 查询条件 -->
            <el-card shadow="hover" style="margin-bottom: 8px">
              <el-form :model="evaluationQuery" inline>
                <el-form-item label="考核期间">
                  <el-date-picker
                    v-model="evaluationQuery.dateRange"
                    type="monthrange"
                    range-separator="至"
                    start-placeholder="开始月份"
                    end-placeholder="结束月份"
                    format="YYYY-MM"
                    value-format="YYYY-MM"
                  />
                </el-form-item>
                <el-form-item label="人员姓名">
                  <el-input
                    v-model="evaluationQuery.name"
                    placeholder="请输入人员姓名"
                    clearable
                    style="width: 150px"
                  />
                </el-form-item>
                <el-form-item label="考核等级">
                  <el-select v-model="evaluationQuery.grade" placeholder="请选择等级" clearable style="width: 120px">
                    <el-option label="优秀" value="excellent" />
                    <el-option label="良好" value="good" />
                    <el-option label="合格" value="qualified" />
                    <el-option label="不合格" value="unqualified" />
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="searchEvaluations">
                    <el-icon><Search /></el-icon>
                    查询
                  </el-button>
                  <el-button @click="resetEvaluationQuery">
                    <el-icon><Refresh /></el-icon>
                    重置
                  </el-button>
                </el-form-item>
              </el-form>
            </el-card>

            <!-- 操作按钮 -->
            <el-card class="operation-card" shadow="hover" style="margin-bottom: 8px">
              <el-row :gutter="10">
                <el-col :span="24">
                  <el-button type="primary" plain @click="handleAddEvaluation">
                    <el-icon><Plus /></el-icon>
                    新增考核
                  </el-button>
                  <el-button type="info" plain @click="evaluationReport">
                    <el-icon><DataAnalysis /></el-icon>
                    考核报告
                  </el-button>
                  <el-button type="success" plain @click="exportEvaluations">
                    <el-icon><Download /></el-icon>
                    导出考核
                  </el-button>
                </el-col>
              </el-row>
            </el-card>

            <!-- 考核评价表格 -->
            <el-card shadow="hover">
              <el-table :data="evaluationList" border>
                <el-table-column prop="name" label="人员姓名" width="120" />
                <el-table-column prop="department" label="所属部门" width="120" />
                <el-table-column prop="evaluationPeriod" label="考核期间" width="150" />
                <el-table-column prop="responsibilityScore" label="责任履行" width="100">
                  <template #default="{ row }">
                    <span :class="getScoreClass(row.responsibilityScore)">
                      {{ row.responsibilityScore }}分
                    </span>
                  </template>
                </el-table-column>
                <el-table-column prop="taskCompletion" label="任务完成" width="100">
                  <template #default="{ row }">
                    <span :class="getScoreClass(row.taskCompletion)">
                      {{ row.taskCompletion }}分
                    </span>
                  </template>
                </el-table-column>
                <el-table-column prop="totalScore" label="总分" width="80">
                  <template #default="{ row }">
                    <span :class="getScoreClass(row.totalScore)">
                      {{ row.totalScore }}分
                    </span>
                  </template>
                </el-table-column>
                <el-table-column prop="grade" label="考核等级" width="100">
                  <template #default="{ row }">
                    <el-tag :type="getGradeTag(row.grade)">
                      {{ getGradeText(row.grade) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="evaluator" label="考核人" width="100" />
                <el-table-column prop="evaluationDate" label="考核时间"/>
                <el-table-column label="操作" width="280" fixed="right">
                  <template #default="{ row }">
                    <el-button link type="primary" @click="viewEvaluationDetail(row)">
                      <el-icon><View /></el-icon>
                      查看
                    </el-button>
                    <el-button link type="primary" @click="handleEditEvaluation(row)">
                      <el-icon><Edit /></el-icon>
                      编辑
                    </el-button>
                    <el-button link type="danger" @click="deleteEvaluation(row)">
                      <el-icon><Delete /></el-icon>
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>

              <!-- 分页 -->
              <div class="pagination-section">
                <Pagination
                  :total="evaluationPagination.total"
                  v-model:page="evaluationPagination.currentPage"
                  v-model:limit="evaluationPagination.pageSize"
                  @pagination="handleEvaluationPagination"
                />
              </div>
            </el-card>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 责任表单对话框 -->
    <ResponsibilityFormDialog
      v-model:visible="responsibilityDialogVisible"
      :responsibility-data="currentResponsibility"
      @success="handleResponsibilityFormSuccess"
    />

    <!-- 人员分配对话框 -->
    <AssignmentFormDialog
      v-model:visible="assignmentDialogVisible"
      :assignment-data="currentAssignment"
      @success="handleAssignmentFormSuccess"
    />

    <!-- 考核评价对话框 -->
    <EvaluationFormDialog
      v-model:visible="evaluationDialogVisible"
      :evaluation-data="currentEvaluation"
      @success="handleEvaluationFormSuccess"
    />

    <!-- 责任详情对话框 -->
    <ResponsibilityDetailDialog
      v-model:visible="detailDialogVisible"
      :responsibility-data="currentDetail"
      @edit="handleDetailEdit"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  User,
  CircleCheck,
  Clock,
  SuccessFilled,
  Search,
  Refresh,
  Plus,
  Download,
  Grid,
  View,
  Edit,
  Delete,
  UserFilled,
  Operation,
  Setting,
  DataAnalysis
} from '@element-plus/icons-vue'
import Pagination from '@/components/Pagination/index.vue'
import ResponsibilityFormDialog from './components/ResponsibilityFormDialog.vue'
import AssignmentFormDialog from './components/AssignmentFormDialog.vue'
import EvaluationFormDialog from './components/EvaluationFormDialog.vue'
import ResponsibilityDetailDialog from './components/ResponsibilityDetailDialog.vue'

// 对话框显示状态
const responsibilityDialogVisible = ref(false)
const assignmentDialogVisible = ref(false)
const evaluationDialogVisible = ref(false)
const detailDialogVisible = ref(false)

// 当前编辑的数据
const currentResponsibility = ref(null)
const currentAssignment = ref(null)
const currentEvaluation = ref(null)
const currentDetail = ref(null)

// 当前激活的标签页
const activeTab = ref('responsibilities')

// 统计数据
const statistics = reactive({
  totalPersonnel: 45,
  activeResponsibilities: 128,
  pendingTasks: 23,
  completedTasks: 156
})

// 责任清单查询条件
const responsibilityQuery = reactive({
  name: '',
  type: '',
  level: '',
  status: ''
})

// 人员分配查询条件
const assignmentQuery = reactive({
  name: '',
  department: '',
  position: ''
})

// 考核评价查询条件
const evaluationQuery = reactive({
  dateRange: [],
  name: '',
  grade: ''
})

// 责任清单数据
const responsibilityList = ref([])

// 人员分配数据
const assignmentList = ref([])

// 考核评价数据
const evaluationList = ref([])

// 分页信息
const responsibilityPagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

const assignmentPagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

const evaluationPagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 标签页切换
const handleTabChange = (tabName: string) => {
  activeTab.value = tabName
}

// 责任清单相关方法
const searchResponsibilities = () => {
  console.log('搜索责任清单', responsibilityQuery)
}

const resetResponsibilityQuery = () => {
  Object.assign(responsibilityQuery, {
    name: '',
    type: '',
    level: '',
    status: ''
  })
}

const addResponsibility = () => {
  currentResponsibility.value = null
  responsibilityFormVisible.value = true
}

const editResponsibility = (row: any) => {
  currentResponsibility.value = { ...row }
  responsibilityFormVisible.value = true
}

const viewResponsibilityDetail = (row: any) => {
  currentResponsibility.value = row
  responsibilityDetailVisible.value = true
}

const assignResponsibility = (row: any) => {
  ElMessage.info('跳转到人员分配页面')
  activeTab.value = 'assignments'
}

const deleteResponsibility = (row: any) => {
  ElMessageBox.confirm('确定要删除这个责任吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功')
  })
}

const exportResponsibilities = () => {
  ElMessage.success('导出责任清单成功')
}

const responsibilityMatrix = () => {
  ElMessage.info('打开责任矩阵图')
}

// 人员分配相关方法
const searchAssignments = () => {
  console.log('搜索人员分配', assignmentQuery)
}

const resetAssignmentQuery = () => {
  Object.assign(assignmentQuery, {
    name: '',
    department: '',
    position: ''
  })
}

const addAssignment = () => {
  currentAssignment.value = null
  assignmentFormVisible.value = true
}

const editAssignment = (row: any) => {
  currentAssignment.value = { ...row }
  assignmentFormVisible.value = true
}

const viewAssignmentDetail = (row: any) => {
  ElMessage.info('查看人员分配详情')
}

const adjustAssignment = (row: any) => {
  ElMessage.info('调整人员责任分配')
}

const deleteAssignment = (row: any) => {
  ElMessageBox.confirm('确定要删除这个分配吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功')
  })
}

const batchAssign = () => {
  ElMessage.info('批量分配责任')
}

const exportAssignments = () => {
  ElMessage.success('导出人员分配成功')
}

// 考核评价相关方法
const searchEvaluations = () => {
  console.log('搜索考核评价', evaluationQuery)
}

const resetEvaluationQuery = () => {
  Object.assign(evaluationQuery, {
    dateRange: [],
    name: '',
    grade: ''
  })
}

const addEvaluation = () => {
  currentEvaluation.value = null
  evaluationFormVisible.value = true
}

const editEvaluation = (row: any) => {
  currentEvaluation.value = { ...row }
  evaluationFormVisible.value = true
}

const viewEvaluationDetail = (row: any) => {
  ElMessage.info('查看考核评价详情')
}

const deleteEvaluation = (row: any) => {
  ElMessageBox.confirm('确定要删除这个考核记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功')
  })
}

const evaluationReport = () => {
  ElMessage.info('生成考核报告')
}

const exportEvaluations = () => {
  ElMessage.success('导出考核评价成功')
}

// 生成责任清单数据（10-50条）
const loadResponsibilities = async () => {
  await new Promise(resolve => setTimeout(resolve, 200))
  const randInt = (min: number, max: number) => Math.floor(Math.random() * (max - min + 1)) + min
  const types = ['safety', 'maintenance', 'operation', 'management']
  const levels = ['1', '2', '3']
  const departments = ['运行部', '维护部', '管理部', '安全部']
  const statuses = ['active', 'suspended', 'abolished']
  const count = randInt(10, 50)
  const list: any[] = []
  for (let i = 0; i < count; i++) {
    const year = 2023 + randInt(0, 1)
    list.push({
      id: i + 1,
      name: `责任-${i + 1}`,
      code: `ZR-${String(i + 1).padStart(3, '0')}`,
      type: types[randInt(0, types.length - 1)],
      level: levels[randInt(0, levels.length - 1)],
      description: `职责描述-${i + 1}`,
      department: departments[randInt(0, departments.length - 1)],
      assignedCount: randInt(1, 10),
      status: statuses[randInt(0, statuses.length - 1)],
      createTime: `${year}-${String(randInt(1, 12)).padStart(2, '0')}-${String(randInt(1, 28)).padStart(2, '0')} 10:30:00`
    })
  }
  responsibilityList.value = list
  responsibilityPagination.total = list.length
}

// 生成人员分配数据（10-50条）
const loadAssignments = async () => {
  await new Promise(resolve => setTimeout(resolve, 200))
  const randInt = (min: number, max: number) => Math.floor(Math.random() * (max - min + 1)) + min
  const departments = ['运行部', '维护部', '管理部', '安全部']
  const positions = ['运行主管', '维护工程师', '管理员', '专员']
  const count = randInt(10, 50)
  const list: any[] = []
  for (let i = 0; i < count; i++) {
    const respCount = randInt(1, 4)
    const responsibilities = Array.from({ length: respCount }, () => `责任-${randInt(1, 30)}`)
    list.push({
      id: i + 1,
      name: `人员-${i + 1}`,
      employeeId: `EMP-${String(100 + i)}`,
      department: departments[randInt(0, departments.length - 1)],
      position: positions[randInt(0, positions.length - 1)],
      responsibilities,
      responsibilityCount: responsibilities.length,
      phone: `13800${String(randInt(100000, 999999))}`,
      assignDate: `2024-${String(randInt(1, 12)).padStart(2, '0')}-${String(randInt(1, 28)).padStart(2, '0')} 09:00:00`
    })
  }
  assignmentList.value = list
  assignmentPagination.total = list.length
}

// 生成考核评价数据（10-50条）
const loadEvaluations = async () => {
  await new Promise(resolve => setTimeout(resolve, 200))
  const randInt = (min: number, max: number) => Math.floor(Math.random() * (max - min + 1)) + min
  const departments = ['运行部', '维护部', '管理部', '安全部']
  const grades = ['excellent', 'good', 'qualified', 'unqualified']
  const evaluators = ['王经理', '陈主任', '刘主管', '赵经理']
  const count = randInt(10, 50)
  const list: any[] = []
  for (let i = 0; i < count; i++) {
    const responsibilityScore = randInt(70, 100)
    const taskCompletion = randInt(70, 100)
    const totalScore = Number(((responsibilityScore + taskCompletion) / 2).toFixed(1))
    list.push({
      id: i + 1,
      name: `人员-${i + 1}`,
      department: departments[randInt(0, departments.length - 1)],
      evaluationPeriod: `2024-${String(randInt(1, 12)).padStart(2, '0')}`,
      responsibilityScore,
      taskCompletion,
      totalScore,
      grade: grades[randInt(0, grades.length - 1)],
      evaluator: evaluators[randInt(0, evaluators.length - 1)],
      evaluationDate: `2024-${String(randInt(1, 12)).padStart(2, '0')}-${String(randInt(1, 28)).padStart(2, '0')} 10:00:00`
    })
  }
  evaluationList.value = list
  evaluationPagination.total = list.length
}

// 分页处理
const handleResponsibilityPagination = (pagination: any) => {
  Object.assign(responsibilityPagination, pagination)
  searchResponsibilities()
}

const handleAssignmentPagination = (pagination: any) => {
  Object.assign(assignmentPagination, pagination)
  searchAssignments()
}

const handleEvaluationPagination = (pagination: any) => {
  Object.assign(evaluationPagination, pagination)
  searchEvaluations()
}

// 表单成功回调
const handleResponsibilityFormSuccess = () => {
  responsibilityDialogVisible.value = false
  searchResponsibilities()
}

const handleAssignmentFormSuccess = () => {
  assignmentDialogVisible.value = false
  searchAssignments()
}

const handleEvaluationFormSuccess = () => {
  evaluationDialogVisible.value = false
  searchEvaluations()
}

// 对话框处理方法
const handleAddResponsibility = () => {
  currentResponsibility.value = null
  responsibilityDialogVisible.value = true
}

const handleEditResponsibility = (row: any) => {
  currentResponsibility.value = { ...row }
  responsibilityDialogVisible.value = true
}

const handleViewResponsibility = (row: any) => {
  currentDetail.value = { ...row }
  detailDialogVisible.value = true
}

const handleAddAssignment = () => {
  currentAssignment.value = null
  assignmentDialogVisible.value = true
}

const handleEditAssignment = (row: any) => {
  currentAssignment.value = { ...row }
  assignmentDialogVisible.value = true
}

const handleAddEvaluation = () => {
  currentEvaluation.value = null
  evaluationDialogVisible.value = true
}

const handleEditEvaluation = (row: any) => {
  currentEvaluation.value = { ...row }
  evaluationDialogVisible.value = true
}

const handleDetailEdit = (data: any) => {
  currentResponsibility.value = { ...data }
  responsibilityDialogVisible.value = true
}

// 工具方法
const getResponsibilityTypeTag = (type: string) => {
  const tagMap: Record<string, string> = {
    safety: 'danger',
    operation: 'primary',
    maintenance: 'warning',
    management: 'success'
  }
  return tagMap[type] || 'info'
}

const getResponsibilityTypeText = (type: string) => {
  const textMap: Record<string, string> = {
    safety: '安全责任',
    operation: '运行责任',
    maintenance: '维护责任',
    management: '管理责任'
  }
  return textMap[type] || type
}

const getLevelTag = (level: string) => {
  const tagMap: Record<string, string> = {
    '1': 'danger',
    '2': 'warning',
    '3': 'info'
  }
  return tagMap[level] || 'info'
}

const getLevelText = (level: string) => {
  const textMap: Record<string, string> = {
    '1': '一级',
    '2': '二级',
    '3': '三级'
  }
  return textMap[level] || level
}

const getStatusTag = (status: string) => {
  const tagMap: Record<string, string> = {
    active: 'success',
    suspended: 'warning',
    abolished: 'danger'
  }
  return tagMap[status] || 'info'
}

const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    active: '有效',
    suspended: '暂停',
    abolished: '废止'
  }
  return textMap[status] || status
}

const getGradeTag = (grade: string) => {
  const tagMap: Record<string, string> = {
    excellent: 'success',
    good: 'primary',
    qualified: 'warning',
    unqualified: 'danger'
  }
  return tagMap[grade] || 'info'
}

const getGradeText = (grade: string) => {
  const textMap: Record<string, string> = {
    excellent: '优秀',
    good: '良好',
    qualified: '合格',
    unqualified: '不合格'
  }
  return textMap[grade] || grade
}

const getScoreClass = (score: number) => {
  if (score >= 90) return 'score-excellent'
  if (score >= 80) return 'score-good'
  if (score >= 70) return 'score-qualified'
  return 'score-unqualified'
}

onMounted(() => {
  searchResponsibilities()
  loadResponsibilities()
  loadAssignments()
  loadEvaluations()
})
</script>

<style scoped>
.responsibility-management-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.stats-cards {
  margin-bottom: 20px;
}

.stats-card {
  height: 100px;
  cursor: pointer;
  transition: all 0.3s;
}

.stats-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stats-content {
  display: flex;
  align-items: center;
  height: 100%;
  padding: 0 20px;
}

.stats-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  font-size: 24px;
  color: white;
}

.stats-icon.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stats-icon.active {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stats-icon.pending {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stats-icon.completed {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stats-info {
  flex: 1;
}

.stats-value {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  line-height: 1;
  margin-bottom: 8px;
}

.stats-label {
  font-size: 14px;
  color: #909399;
}

.main-content {
  margin-bottom: 20px;
}

.tab-content {
  padding-top: 20px;
}

.query-card {
  margin-bottom: 20px;
}

.mb8 {
  margin-bottom: 8px;
}

.score-excellent {
  color: #67c23a;
  font-weight: 600;
}

.score-good {
  color: #409eff;
  font-weight: 600;
}

.score-qualified {
  color: #e6a23c;
  font-weight: 600;
}

.score-unqualified {
  color: #f56c6c;
  font-weight: 600;
}
</style>